# -*- coding: utf-8 -*-
from osv import fields,osv
from openerp.tools.translate import _
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DATE_FORMAT
from datetime import datetime

class pm_customer_contract_renewal(osv.osv_memory):
    _name = 'pm.customer.contract.renewal'

    def default_get(self,cr,uid,fields,context=None):
        contract_obj = self.pool.get('pm.customer.contract')
        contract_ids = context.get('active_ids',[])
        print 'contract_ids is %s' % contract_ids
        res = super(pm_customer_contract_renewal,self).default_get(cr,uid,fields,context=context)
        contract_item = contract_obj.read(cr,uid,contract_ids[0],['start_date','end_date','partner_id'],context=context)
        print 'contract_item is %s' % contract_item
        res['contract_id'] = contract_ids[0]
        res['source_start_date'] = contract_item['start_date']
        res['source_end_date'] = contract_item['end_date']
        res['partner_id'] = contract_item['partner_id'][0]
        return res

    def renewal(self,cr,uid,ids,context=None):
        renewal_item = self.read(cr,uid,ids[0],context=context)
        contract_rep = self.pool.get('pm.customer.contract')
        contract_item = contract_rep.read(cr,uid,renewal_item['contract_id'][0],['name','room_id','start_date','end_date'],context=context)
        print 'contract_item is %s' % contract_item

        source_end_date = contract_item['end_date']
        new_end_date = renewal_item['new_end_date']
        room_id = contract_item['room_id'][0]

        if datetime.strptime(source_end_date,DATE_FORMAT)>=datetime.strptime(new_end_date,DATE_FORMAT):
            raise osv.except_osv(_('不能续签'),_('续签合同的收费结束日期必须在原合同日期之后！'))

        contract_rep.write(cr,uid,contract_item['id'],{'end_date':new_end_date,
                                                       'remark':u'源自%s的续签合同'%contract_item['name']},context=context)
        crp_rep = self.pool.get('pm.cost.item.room')
        crp_ids = crp_rep.search(cr,uid,[('room_id','=',room_id)],context=context)
        crp_rep.write(cr,uid,crp_ids,{'billing_end_date':new_end_date},context=context)
        self.pool.get('pm.project.building.room').write(cr,uid,room_id,{'in_end_date':new_end_date},context=context)
        return 1

    _columns = {
        'contract_id':fields.many2one('pm.customer.contract',string='租赁合同'),
        'partner_id':fields.related('contract_id',type='many2one',relation='res.partner',string='客户名称'),
        'source_start_date':fields.related('contract_id','start_date',type='date',string='原起租日期'),
        'source_end_date':fields.related('contract_id','end_date',type='date',string='原止租日期'),
        'new_end_date':fields.date(string='收费结束日期',required=True),
    }
pm_customer_contract_renewal()


